﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Media;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.Locations;
using AndroidText = Android.Text;
using Android.Content.Res;
using Android.Content.PM;
using Android.Support.V4.App;

using BugSense;

namespace MWC.NetcampCheckin
{
    [Activity(Label = "NetcampCountTheDistance", NoHistory = true)]
    public class NetcampCountTheDistance : Activity, ILocationListener
    {
        LocationManager _locMgr;
        Location currentLocation;
        Criteria criteria;
        float currentDistance;

        bool isGpsDevice   = false;
        bool isGpsProvider = false;
        bool isNetProvider = false;
        //asd
        protected override void OnCreate(Bundle bundle)
        {
            try
            {
                base.OnCreate(bundle);

                BugSenseHandler.Instance.ClearCrashExtraData();
                BugSense.Core.Model.LimitedCrashExtraDataList extras = BugSenseHandler.Instance.CrashExtraData;

                extras.Add(new BugSense.Core.Model.CrashExtraData
                {
                    Key = "Screen",
                    Value = "NetcampCountTheDistance"
                });

                var prefs = GetSharedPreferences("NetcampApp", 0);
                string userName = prefs.GetString("Name", "");
                //sprawdz czy jest dzien spotkania
                if (DaysManager.GetLastDay().time.DayOfYear != DateTime.Now.DayOfYear)
                {
                    SetContentView(Resource.Layout.NetcampIsTooEarly);
                    TextView info = FindViewById<TextView>(Resource.Id.info);
                    DateTime thisDay = DaysManager.GetLastDay().time;
                    string dateString = thisDay.ToString("dd.MM");
                    if (userName != "")
                    {
                        info.Text = String.Format("{0}, cieszymy się, że {1} będziesz z nami", userName, dateString);
                    }
                    else
                    {
                        info.Text = String.Format("Witaj, cieszymy się, że {0} będziesz z nami", dateString);
                    }
                }
                else
                {
                    SetContentView(Resource.Layout.NetcampCountTheDistance);
                    //string text = Intent.GetStringExtra("FirstData") ?? "Data not available";

                    //MWCApp.LogDebug("ustaw location manager");
                    //ustaw location manager
                    _locMgr = GetSystemService(Context.LocationService) as LocationManager;

                    isGpsDevice = this.PackageManager.HasSystemFeature(PackageManager.FeatureLocationGps);
                    isGpsProvider = _locMgr.IsProviderEnabled(LocationManager.GpsProvider);
                    isNetProvider = _locMgr.IsProviderEnabled(LocationManager.NetworkProvider);

                    if (isGpsProvider)
                        _locMgr.RequestLocationUpdates(LocationManager.GpsProvider, 2000, 2, this);
                    else if (isGpsDevice)
                        NetcampAlerts.TurnOnGPS(this);
                    else
                        _locMgr.RequestLocationUpdates(LocationManager.NetworkProvider, 2000, 0, this);
                    //MWCApp.LogDebug("Żądanie aktualizacji położenia które trafia jako obiekt Location do OnLocationChanged");
                    // Żądanie aktualizacji położenia które trafia jako obiekt Location do OnLocationChanged


                    CheckBox checkbox = FindViewById<CheckBox>(Resource.Id.checkBox);
                    TextView name = FindViewById<TextView>(Resource.Id.Name);
                    TextView distance = FindViewById<TextView>(Resource.Id.distance);
                    Button checkin = FindViewById<Button>(Resource.Id.checkIn);
                    TextView place = FindViewById<TextView>(Resource.Id.place);
                    TextView street = FindViewById<TextView>(Resource.Id.street);
                    //MWCApp.LogDebug("Intent.GetStringExtra(\"FirstData\")");

                    place.Text = DaysManager.GetLastDay().title;
                    street.Text = DaysManager.GetLastDay().address;

                    String s = "Miło nam że jesteś!\n Zamelduj się, a szybko przejdziesz przez punkt rejestracji!";

                    name.TextFormatted = AndroidText.Html.FromHtml(s);

                    MediaPlayer _player;
                    //MWCApp.LogDebug("_player = MediaPlayer.Create(this, Resource.Raw.Reminder);");
                    _player = MediaPlayer.Create(this, Resource.Raw.Reminder);
                    //Vibrator v = (Vibrator)GetSystemService(Context.VibratorService);
                    //MWCApp.LogDebug("after _player ");
                    TextView[] tabOfNormalItems = new TextView[5];
                    int iterator = 0;
                    tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.infoAboutMeeting);
                    tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.place);
                    tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.street);
                    tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.distance);
                    tabOfNormalItems[iterator++] = FindViewById<TextView>(Resource.Id.Name);

                    setFont("fonts/texgyreheros-regular-webfont.ttf", tabOfNormalItems, TypefaceStyle.Normal);

                    byte[] imageBytesArray = DaysManager.GetImageByteArray();
                    Drawable background = new BitmapDrawable(Resources, BitmapFactory.DecodeByteArray(imageBytesArray, 0, imageBytesArray.Length));

                    checkbox.Visibility = ViewStates.Gone;
                    LinearLayout _linBackground = FindViewById<LinearLayout>(Resource.Id.firstBackground);
                    _linBackground.SetBackgroundDrawable(background);

                    //przejscie do kolejnego Activity, po nacisnieciu checkIn
                    Button ci = FindViewById<Button>(Resource.Id.checkIn);
                    if (currentDistance > 0 && currentDistance < 2000)
                    {
                        ci.Visibility = ViewStates.Visible;
                        name.Visibility = ViewStates.Visible;
                        distance.Visibility = ViewStates.Gone;
                    }
                    else
                    {
                        ci.Visibility = ViewStates.Gone;
                    }

                    ci.Click += delegate
                    {
                        var prefsEditor = prefs.Edit();
                        prefsEditor.PutInt("CurrentStep", 3);
                        prefsEditor.PutBoolean("Checked", true);
                        prefsEditor.Commit();
                        var netcampLastStep = new Intent(this, typeof(NetcampLastStep));
                        StartActivity(netcampLastStep);
                        Finish();
                    };
                }
            }
            catch (Exception e)
            {
                MWCApp.LogDebug(e);
                NetcampAlerts.UnknownError(this);
            }
        }
            // 1 - sciezka do czcionki, 2 - tablica, 3 - Typ:Bold,Italic,Normal,BoldItalic
        private void setFont(string path, TextView[] tTV, TypefaceStyle Type)
        {
            AssetManager mgr;
            mgr = Assets;
            Typeface font = Typeface.CreateFromAsset(mgr, path);
            for (int i = 0; i < tTV.Length; i++)
            {
                tTV[i].SetTypeface(font, Type);
            }

        }
        protected override void OnPause()
        {
            base.OnPause();
            if (DaysManager.GetLastDay().time.DayOfYear == DateTime.Now.DayOfYear)
            {
                _locMgr.RemoveUpdates(this);
            }
        }

        protected override void OnResume()
        {
            base.OnResume();
            if (DaysManager.GetLastDay().time.DayOfYear == DateTime.Now.DayOfYear)
            {
                if (isGpsProvider)
                    _locMgr.RequestLocationUpdates(LocationManager.GpsProvider, 2000, 2, this);
                else if (isGpsDevice)
                    NetcampAlerts.TurnOnGPS(this);
                else
                    _locMgr.RequestLocationUpdates(LocationManager.NetworkProvider, 2000, 0, this);
            }
        }

        public void OnLocationChanged(Location location)
        {
                //MWCApp.LogDebug("Metoda OnLocationChanged");
                Button ci = FindViewById<Button>(Resource.Id.checkIn);
                TextView name = FindViewById<TextView>(Resource.Id.Name);
                TextView distance = FindViewById<TextView>(Resource.Id.distance);

                currentDistance = distFrom(location.Latitude, location.Longitude, Constants.MapPinLatitude, Constants.MapPinLongitude);
                if (currentDistance > 0 && currentDistance <= 2000)
                {
                    ci.Visibility = ViewStates.Visible;
                    name.Visibility = ViewStates.Visible;
                    distance.Visibility = ViewStates.Gone;
                }
                else
                {
                    ShowDistance(currentDistance);
                } 
        }

        // Kolejne metody wymagane przez interface ILocationListener
        public void OnProviderDisabled(string provider)
        {
            if (provider == LocationManager.GpsProvider)
                isGpsProvider = false;
            else if (provider == LocationManager.NetworkProvider)
                isNetProvider = false;

            _locMgr.RemoveUpdates(this);

            if (isGpsProvider)
                _locMgr.RequestLocationUpdates(LocationManager.GpsProvider, 2000, 2, this);
            else if (isNetProvider)
                _locMgr.RequestLocationUpdates(LocationManager.NetworkProvider, 2000, 0, this);
        }

        public void OnProviderEnabled(string provider)
        {
            if (provider == LocationManager.GpsProvider)
                isGpsProvider = true;
            else if (provider == LocationManager.NetworkProvider)
                isNetProvider = true;

            _locMgr.RemoveUpdates(this);

            if (isGpsProvider)
                _locMgr.RequestLocationUpdates(LocationManager.GpsProvider, 2000, 2, this);
            else if (isNetProvider)
                _locMgr.RequestLocationUpdates(LocationManager.NetworkProvider, 2000, 0, this);
        }

        public void OnStatusChanged(string s, Availability i, Bundle extras)
        {
        }

        public static float distFrom(double lat1, double lng1, double lat2, double lng2)
        {
            double earthRadius = 6369000;
            double dLat = DegreeToRadian(lat2 - lat1);
            double dLng = DegreeToRadian(lng2 - lng1);
            double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
                       Math.Cos(DegreeToRadian(lat1)) * Math.Cos(DegreeToRadian(lat2)) *
                       Math.Sin(dLng / 2) * Math.Sin(dLng / 2);
            double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
            double dist = earthRadius * c;

            return (float)dist;
        }

        public void ShowDistance(float distance)
        {
            string message = null;
            TextView distanceText = FindViewById<TextView>(Resource.Id.distance);
            if (distance == 0)
            {
                distanceText.Text = "Nie udało się zlokalizować odległości od miejsca wydarzenia";
            }
            else if (distance > 0 && distance < 2000)
            {
                distanceText.Visibility = ViewStates.Gone;
            }
            else if (distance < 1000)
            {
                message = String.Format("Twoja odległość to {0:0.00} m od miejsca spotkania w odległości mniejszej niż 500 metrów uaktywni się przycisk checkin", distance);
            }
            else
            {
                message = String.Format("Twoja odległość to {0:0.00} km od miejsca spotkania w odległości mniejszej niż 500 metrów uaktywni się przycisk checkin", distance / 1000);
            }
            
            distanceText.Text = message;
        }

        private static double DegreeToRadian(double angle)
        {
            return Math.PI * angle / 180.0;
        }

    }
          
}